#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C mylcd(0X3F,16,2);

volatile unsigned int counter = 0;  // Counter variable for revolutions
unsigned long previousMillis = 0;  // Variable to store previous time
unsigned int rpm = 0;  // Variable to store RPM value
unsigned int gs = 1; //格栅数量

void IRinterrupt() {
  counter++;
  //Serial.println("1");
}

void setup() {
  Serial.begin(9600);

  mylcd.init();
  mylcd.backlight();
  
  attachInterrupt(digitalPinToInterrupt(3), IRinterrupt, FALLING);
  //detachInterrupt(digitalPinToInterrupt(3));
  delay(1000);
}

void loop() {
  
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= 1000) {

    mylcd.clear();
    
    detachInterrupt(digitalPinToInterrupt(3));
    rpm = (counter / gs) * 60;  // Calculate RPM
    counter = 0;
    attachInterrupt(digitalPinToInterrupt(3), IRinterrupt, FALLING);
    previousMillis = currentMillis;

    Serial.println(rpm);

    mylcd.setCursor(0, 0);
    mylcd.print("RPM : ");    // 打印文字
    mylcd.print(rpm);    // 输出变量的值
  }
  
}
